from selenium.webdriver.support.ui import WebDriverWait
import time
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.select import Select

class Base():
    def __init__(self, driver):
        self.driver=driver
    def open_url(self, url):
        self.driver.get(url)
    def find_element(self, loc):
        # 截屏时间戳
        nowtime=time.strftime('%Y%m%d%H%M%S')
        # 异常处理
        try:
            #  显式等待
            WebDriverWait(self.driver, 20, 0.5).until(lambda driver: self.driver.find_element(*loc).is_displayed())
            return self.driver.find_element(*loc)
        except Exception as e:
            # 出错截屏
            self.driver.save_screenshot(nowtime+'error.png')
            print('出错啦！',str(e))


    def click(self, loc):
        self.find_element(loc).click()



    def send_keys(self, loc, info):
        self.find_element(loc).send_keys(info)

    # 进入frame框架
    def to_frame(self,loc):
        self.driver.switch_to.frame(self.find_element(loc))
    # 页面滑动的方法
    def scroll(self,num):
        self.driver.execute_script(f'Window.scrollTo(0,{num})')


    # 弹窗处理方法 1
    def alert_operation1(self):
        alert = self.driver.switch_to.alert
        alert.accept()
    # 弹窗处理方法 2
    def alert_operation2(self,text):
        alert = self.driver.switch_to.alert
        alert.send_keys(text)

    # 弹窗处理方法 3
    def alert_operation3(self):
        alert = self.driver.switch_to.alert
        alert.dismiss()
    # 切换窗口
    def new_window(self):
        self.driver.switch_to.window(self.driver.window_handles[-1])


    # 浏览器事件 设置页面大小
    def set_window_size(self,x,y):
        self.driver.set_window_size(x,y)


    # 键盘回车事件
    def enter(self,loc):
        self.send_keys(loc,Keys.ENTER)


    # 下拉框处理
    def select_value(self,loc,value):
        Select(self.find_element(loc)).deselect_by_value(value)
    # 鼠标事件 鼠标悬浮
    def move_toelement(self,loc):
        ActionChains(self.driver).move_to_element(self.find_element(loc))
    def get_text(self,loc):
       return self.find_element(loc).text





